package com.sup.servlet;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sup.entity.Project;
import com.sup.entity.User;

/**
 * Servlet implementation class ShowProfilServlet
 */
@WebServlet("/auth/showProfil")
public class ShowProfilServlet extends HttpServlet {
	private static EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowProfilServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init()
    {
    	emf = Persistence.createEntityManagerFactory("PersistenceUnit");
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = emf.createEntityManager();
		String idUser = (String) request.getSession().getAttribute("idUser");
		
		Query infoUser = em.createQuery("Select User FROM User user WHERE idUser = "+idUser);
		request.setAttribute("infoUser", infoUser.getSingleResult());
		
		Query projectUser = em.createQuery("SELECT Project from Project project WHERE idUser ="+idUser);
		List<Project> projects = projectUser.getResultList();
		request.setAttribute("projectUser",projects);
		
		request.getRequestDispatcher("/auth/showProfil.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManager em = emf.createEntityManager();
		
		String idUser = (String) request.getSession().getAttribute("idUser");
		
		Query userInfo = em.createQuery("SELECT User from User user WHERE idUser ="+idUser);
		
		User user = (User) userInfo.getSingleResult();
		user.setIdUser(idUser);
		user.setAdmin(0);
		user.setName(request.getParameter("name"));
		user.setFirstname(request.getParameter("firstname"));
		user.setEmail(request.getParameter("email"));
				
		em.getTransaction().begin();
	    em.merge(user);
	    em.getTransaction().commit();
	    em.close();
	    
	    request.setAttribute("modified", true);
	    doGet(request,response);
	}

}
